<!--
 * @Author: xxx
 * @Description: 导出
-->
<template>
  <div class="ExportBuuton">
    <el-button @click="buttonExport('exportTable')" class="derive" type="primary"
      >导出</el-button
    >
    <el-table
      id="exportTable"
      style="width: 100%"
      border
      v-show="false"
      :data="copyTable"
    >
      <el-table-column type="index" :align="'center'" width="50" />
      <el-table-column
        v-for="(itemColum, indexColum) in tableColumShowList"
        :key="indexColum"
        :prop="itemColum.prop"
        :label="itemColum.label"
        :min-width="180"
        >
        <template #default="scope">
          <span v-if="itemColum.prop === 'cover'">
          <el-image
            :preview-teleported="true"
            style="width: 60px; height: 60px"
            :src="scope.row[itemColum.prop]"
            :preview-src-list="[scope.row[itemColum.prop]]"
            :initial-index="0"
            fit="cover"
          >
          </el-image>
        </span>
        <span v-if="itemColum.prop === 'qrcode_img'">
          <el-image
            :preview-teleported="true"
            style="width: 60px; height: 60px"
            :src="scope.row[itemColum.prop]"
            :preview-src-list="[scope.row[itemColum.prop]]"
            :initial-index="0"
            fit="cover"
          >
          </el-image>
        </span>
            <span v-else-if="itemColum.prop === 'audio_frequency'||itemColum.prop === 'video'"
          ><a
            :href="scope.row.audio_frequency">点此播放</a
          ></span
        >
        <span v-else>{{scope.row[itemColum.prop]}}</span
        >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { $get} from "@/api/Api.js";
import * as XLSX from "xlsx";
import { nextTick, ref, toRefs, onMounted } from "vue";
import utilHelper from "@/libs/UtilHelper";
import {
  $fullUrl,
  formatDate,
  $banseUrl,
} from "@/utils/utils.js";
let props = defineProps({
  tableDataList: {
    type: Array,
    default() {
      return [];
    },
  },
  tableColumShowList: {
    type: Array,
    default() {
      return [];
    },
  },
  title: {
    type: String,
    default() {
      return "导出";
    },
  },
});

let { tableDataList, tableColumShowList } = toRefs(props);
let copyTable = ref([]);
let list_user = ref([]);
// 获取商城卖家用户列表
let get_list_user = async () => {
  let json = await $get("/api/user/get_list");
  if (json.result && json.result.list) {
    list_user.value = json.result.list;
  } else if (json.error) {
    console.error(json.error);
  }
};
// 查询数组对象某个是否包含某个值,返回对应对象
let getObj = (arr, val) => {
  let obj = arr.find((item) => item.user_id == val);
  if (obj) {
    return obj;
  } else {
    return "-";
  }
};
let initTable=()=>{
  copyTable.value = utilHelper.cloneDeep(tableDataList.value);
  tableColumShowList.value.forEach((itemField) => {
    let { fieldType, label, prop } = itemField;
    // 4:为枚举
    if (fieldType === 2) {
      copyTable.value.forEach((itemRow) => {
        itemRow[prop] = getObj(list_user.value, itemRow[prop]).nickname;
      });
    }
    if (fieldType === 3) {
      copyTable.value.forEach((itemRow) => {
        itemRow[prop] = formatDate(itemRow[prop]);
      });
    }
    if (fieldType === 4) {
      copyTable.value.forEach((itemRow) => {
        itemRow[prop] = $fullUrl($banseUrl,itemRow[prop]);
      });
    }
  });
}
//导出表格
let  buttonExport = (tableid) => {
    initTable()
    nextTick(()=>{
   
  var idTmr;
  function getExplorer() {
    let explorer = window.navigator.userAgent;
    //ie
    if (explorer.indexOf("MSIE") >= 0) {
      return "ie";
    }
    //firefox
    else if (explorer.indexOf("Firefox") >= 0) {
      return "Firefox";
    }
    //Chrome
    else if (explorer.indexOf("Chrome") >= 0) {
      return "Chrome";
    }
    //Opera
    else if (explorer.indexOf("Opera") >= 0) {
      return "Opera";
    }
    //Safari
    else if (explorer.indexOf("Safari") >= 0) {
      return "Safari";
    }
  }
  function Cleanup() {
    window.clearInterval(idTmr);
    CollectGarbage();
  }
  let tableToExcel = (function () {
    let uri = "data:application/vnd.ms-excel;base64,",
      template =
        '<html><head><meta charset="UTF-8"></head><body><table  border="1">{table}</table></body></html>',
      base64 = function (s) {
        return window.btoa(unescape(encodeURIComponent(s)));
      },
      format = function (s, c) {
        return s.replace(/{(\w+)}/g, function (m, p) {
          return c[p];
        });
      };
    return function (table, name) {
      if (!table.nodeType) table = document.getElementById(table);
      let ctx = {
        worksheet: name || "Worksheet",
        table: table.innerHTML,
      };
      window.location.href = uri + base64(format(template, ctx));
    };
  })();
  if (getExplorer() == "ie") {
    let curTbl = document.getElementById(tableid);
    let oXL = new ActiveXObject("Excel.Application");
    let oWB = oXL.Workbooks.Add();
    let xlsheet = oWB.Worksheets(1);
    let sel = document.body.createTextRange();
    sel.moveToElementText(curTbl);
    sel.select();
    sel.execCommand("Copy");
    xlsheet.Paste();
    oXL.Visible = true;

    try {
      let fname = oXL.Application.GetSaveAsFilename(
        "Excel.xls",
        "Excel Spreadsheets (*.xls), *.xls"
      );
    } catch (e) {
      print("Nested catch caught " + e);
    } finally {
      oWB.SaveAs(fname);
      oWB.Close((savechanges = false));
      oXL.Quit();
      oXL = null;
      idTmr = window.setInterval("Cleanup();", 1);
    }
  } else {
    tableToExcel(tableid);
  } 
    })
};
onMounted(() => {
  // 初始化
  get_list_user();
});
</script>

<style lang="less" scoped>
.ExportBuuton {
  .icon-wrapper {
    cursor: pointer;
    margin-left: 10px;
    position: relative;
    width: 32px;
    height: 32px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 4px;
    transition: 0.3s;
    border: 1px solid transparent;
    &:hover {
      box-shadow: 0px 4px 6px 0px #4caaa2;
      i {
        color: #4caaa2;
      }
    }
  }
}
</style>
